using System;
using System.Collections.Generic;
using PowerSearch.Core;
using System.Xml;
using System.IO;

namespace PowerSearch.AppServices.Parser.Provider
{
	public class WikipediaParser : BaseFeedParser
	{
		public override string BaseUrl { get { return "http://en.wikipedia.org/w/api.php?action=opensearch&search={0}&format=xml"; } }

		internal protected override IList<Feed> ParseFeed(string responseData)
		{
			IList<Feed> feedList = null;

			var xmlReader = XmlReader.Create(new StringReader(responseData));
			while (xmlReader.Read())
			{
				if ((xmlReader.NodeType == XmlNodeType.Element)
				    && (xmlReader.Name == "Item"))
				{
					string title = string.Empty;
					string description = string.Empty;
					string displayurl = string.Empty;
					string clickurl = string.Empty;


					bool moreRecords = false;
					do
					{
						moreRecords = xmlReader.Read();
						switch (xmlReader.Name)
						{
							case "Text":
						{
							title = xmlReader.ReadString();
							break;
						}
							case "Description":
						{
							description = xmlReader.ReadString();
							break;
						}
							case "Image":
						{
							displayurl = xmlReader.GetAttribute("Image");
							break;
						}
							case "Url":
						{
							clickurl = xmlReader.ReadString();
							break;
						}
						}
					} while (moreRecords && xmlReader.Name != "Item");

					if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(clickurl))
					{
						if (feedList == null)
							feedList = new List<Feed>();
						feedList.Add(new Feed { Title = title, Description = description, DisplayUrl = displayurl, ClickUrl = clickurl });
					}
				}

			}
			return feedList;
		}
	}
}

